package com.example.day24_h265spsparse;

/**
 * Description:h265 的SPS 解析
 * Created by Gdu on 2020/12/23 9:44.
 */

public class Main {
    public static void main(String[] args) {
        byte[] h265=hexStringToByteArray("42 01 01 01 60 00 00 03 00 B0 00 00 03 00 00 03 00 5A A0 04 42 00 F0 77 E5 AE E4 C9 2E A5 20 A0 C0 C0 5D A1 42 50".replace(" ", ""));
//    //        宽高  在 148位
        nStartBit = 148;
        int width = parseCode(h265);
        int height = parseCode(h265);
        System.out.println("width is "+width+"  --- height  "+height);
    }


    static int nStartBit;

    public static int parseCode(byte[] pBuff) {
        int nZeroNum = 0;
        while (nStartBit < pBuff.length * 8) {
            if ((pBuff[nStartBit / 8] & (0x80 >> (nStartBit % 8))) != 0) {//找到分隔符1
                break;
            }
            nZeroNum++;
            nStartBit++;
        }
        nStartBit++;
        int dwRet = 0;
        for (int i = 0; i < nZeroNum; i++) {
            dwRet <<= 1;
            if ((pBuff[nStartBit / 8] & (0x80 >> (nStartBit % 8))) != 0) {//如果尾数等于1，把1加上
                dwRet += 1;
            }
            nStartBit++;
        }
        int value = (1 << nZeroNum) + dwRet - 1;
        return value;
    }

    //region 把十六进制的字符串转化成字符数组
    public static byte[] hexStringToByteArray(String s) {
        s = s.replace(" ", "");//去掉空格
        //十六进制转byte数组
        int len = s.length();
        byte[] bs = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            bs[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
        }
        return bs;
    }
    //endregion

}
